<template>
  <page-header-wrapper :key="key">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="姓名">
                <a-input v-model="queryParam.name" placeholder="请输入用户姓名" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <a-input v-model="queryParam.phone" placeholder="请输入手机号码" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="用户ID">
                <a-input v-model="queryParam.id" placeholder="请输入用户ID" />
              </a-form-item>
            </a-col>
            <!-- <a-col :md="(!advanced && 8) || 24" :sm="24"> -->
            <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns | columnsFilter"
        :data="loadData"
        showPagination="auto"
        :scroll="{ x: true }"
        :pagination="{ 'show-total': (total) => `Total ${total} items` }"
      >
        <span slot="action" slot-scope="text, record">
          <template>
            <span>
              <a @click="handleRecharge(record)">充值</a>
              <a-divider type="vertical" />
            </span>
            <span>
              <a @click="handleUserUnitPrice(record)">用户产品单价</a>
              <a-divider type="vertical" />
            </span>
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
            </span>
            <span>
              <a @click="handleFreeze(record, record.status)">{{ record.status == 1 ? '冻结' : '解冻' }}</a>
              <a-divider type="vertical" />
            </span>
            
            <span>
              <a @click="handleDel(record)">删除</a>
            </span>
            <!-- <span v-action:user_update> -->
          </template>
        </span>
        <span slot="address" slot-scope="text, scope">
          <span>{{ `${scope.country || 'x'}-${scope.province || 'x'}-${scope.city || 'x'}` }}</span>
        </span>
        <span slot="headImg" slot-scope="text">
          <img v-if="text" :src="`${baseUrl}/${text}`" alt="" class="tableImg headImg" />
          <img
            v-else
            src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            alt=""
            class="tableImg headImg"
          />
        </span>
        <span slot="status" slot-scope="text">
          <a-badge
            :color="text | statusFilter(userStatusList, 'status')"
            :text="text | statusFilter(userStatusList, 'name')"
          />
        </span>
        <span slot="type" slot-scope="text">
          <a-badge
            :color="text | statusFilter(userTypeList, 'status')"
            :text="text | statusFilter(userTypeList, 'name')"
          />
        </span>
        <span slot="sex" slot-scope="text">
          <a-badge v-if="text == 1" status="processing" text="男" />
          <a-badge v-else status="error" text="女" />
        </span>
      </s-table>
      <user-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <recharge-form
        ref="rechargeModal"
        :visible="recharge.visible"
        :loading="recharge.confirmLoading"
        :model="recharge.mdl"
        @cancel="handleRechargeCancel"
        @ok="handleRechargeOk"
      />
      <unit-price-list
        ref="productPricesModal"
        :visible="productPrices.visible"
        :list="productPrices.list"
        @ok="handleProductPricesOk"
        @cancel="handleProductPricesOk"
        
      >
      </unit-price-list>
    </a-card>
  </page-header-wrapper>
  <!-- <page-header-wrapper v-else> -->
  <!-- <router-view :key="key" v-else></router-view> -->
  <!-- </page-header-wrapper> -->
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import { getUserListApi, userAddApi, userUpdateApi } from '@/api/login'
import { userTypeList, userStatusList } from '@/utils/other'
import { mapGetters } from 'vuex'
import { roleByNoAuth } from '@/api/noAuth'
import { updateSmsBalance } from '@/api/finance'

// import StepByStepModal from './modules/StepByStepModal'
import UserForm from './modules/UserForm'
import RechargeForm from './modules/RechargeForm'
import UnitPriceList from './modules/UnitPriceList'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 150,
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  // {
  //   title: '账号',
  //   dataIndex: 'account',
  //   key: 'account',
  //   width: 150,
  // },
  {
    title: '手机号码',
    dataIndex: 'phone',
    customRender: (text) => text || '--',
  },
  {
    title: '余额(元)',
    dataIndex: 'balance',
     width: 150,
    key: 'balance',
    sorter: true,
    // sort: 'balance'
  },
  // {
  //   title: '单价',
  //   dataIndex: "unitPrice",
  //   key: "unitPrice",
  // },

  {
    title: '最后登录时间',
    dataIndex: 'lastLoginTime',
    customRender: (text) => text || '--',
  },
  {
    title: '最后登录Ip',
    dataIndex: 'lastLoginIp',
    customRender: (text) => text || '--',
  },
  // {
  //   title: '添加人',
  //   dataIndex: 'addUserName',
  //   customRender: (text) => text || '--',
  // },
  {
    title: '注册时间',
    dataIndex: 'addTime',
    width: 150,
    customRender: (text) => text || '--',
  },
  // {
  //   title: '最后编辑人',
  //   dataIndex: 'lastUpdateUserName',
  //   check: false,
  //   customRender: (text) => text || '--',
  // },
  // {
  //   title: '最后编辑时间',
  //   dataIndex: 'lastUpdateTime',
  //   check: false,
  //   customRender: (text) => text || '--',
  // },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'AWM-userList',
  components: {
    STable,
    UserForm,
    RechargeForm,
    UnitPriceList
  },
  data() {
    // this.columns = columns
    return {
      value: 1,
      projectTypeList: [],
      projectTypeList1: [],
      pathName: '',
      columns,
      timeout: null,
      inviteUserList: [],
      fetching: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      CG: {
        visible: false,
        confirmLoading: false,
        mdl: null,
      },
      recharge: {
        visible: false,
        confirmLoading: false,
        mdl: null,
      },
      work: {
        visible: false,
        userId: null,
      },
      structure: {
        visible: false,
        userId: null,
      },
      productPrices:{
        list: [],
        visible: false
      },
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParam: {},
      levelList: [], //  等级
      roleList: [], // 权限列表
      studioList: [], //  工作室列表
      // 状态
      userStatusList,
      //  角色类型
      userTypeList,
      // 排序
      sortJ: {
        balance: 'ba.sms_balance',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        const requestParameters = Object.assign(parameter, this.queryParam)
        return getUserListApi(requestParameters).then((res) => {
          let result = {
            data: res.data.data,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      table: {
        data: [],
        loading: false,
        // pagination:{pageSize: 10, current: 1},
        pagination: {},
        columns: [],
        filters: null,
        sorter: null,
        key: 0,
        current: 1,
      },
      selectedRowKeys: [],
      selectedRows: [],
      key: 0,
    }
  },
  filters: {
    columnsFilter: function (a) {
      if (a) {
        return a.filter((v) => v.check || v.check == undefined)
      } else {
        return []
      }
      //this.columns.filter(v=>v.check || v.check == undefined)
    },
  },
  created() {},
  computed: {
    ...mapGetters({ baseUrl: 'baseUrl' }),
  },
  methods: {
    onChange() {},
    handleCeshi(record) {
      this.ceshi.visible = true
      this.ceshi.mdl = null
    },
    handleSearch() {
      this.$refs.table.refresh(true)
    },
    handleDeleteCu() {
      this.columns.splice(1, 1)
      // this.table.key ++;
      this.$forceUpdate()
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    ModalCB(a_key, a_bool) {
      let self = this
      let item = self[a_key]
      const form = self.$refs[`${a_key}Modal`].form
      form.resetFields()
      item.visible = false
      item.confirmLoading = false
      a_bool && self.$refs.table.refresh()
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          values.type = 2
          if (values.id > 0) {
            userUpdateApi(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            userAddApi(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },

    handleRecharge(record) {
      this.recharge.visible = true
      this.recharge.mdl = { ...record }
    },
    handleRechargeCancel() {
      this.recharge.visible = false
      const form = this.$refs.rechargeModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleRechargeOk() {
      const form = this.$refs.rechargeModal.form
      this.recharge.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
            updateSmsBalance(values)
              .then((res) => {
                this.ModalCB('recharge', true)
                this.$message.success('充值成功!')
              })
              .catch((err) => {
                this.ModalCB('recharge', false)
              })
        } else {
          this.recharge.confirmLoading = false
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    handleDel(a_record) {
      let self = this
      const modal = self.$confirm({
        title: '用户删除',
        content: `是否删除用户:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal, -1),
        onCancel: () => {},
      })
    },
    handleFreeze(a_record, a_status) {
      let self = this
      const modal = self.$confirm({
        title: `用户${a_status == 1 ? '冻结' : '解冻'}`,
        content: `是否${a_status == 1 ? '冻结' : '解冻'}用户:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal, a_status == 1 ? 2 : 1),
        onCancel: () => {},
      })
    },
    handleDeleteRole(a_id, a_modal, a_type) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: a_type }
        userUpdateApi(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
    handleRelieveSave(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id }
        userUpdateApi(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('操作成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
    handleChnageColumn(a_columns) {
      this.columns = a_columns
    },
    // 用户产品单价
    handleUserUnitPrice(a_record){
      this.productPrices = {
        list: a_record.productPrices || [],
        visible: true
      }
    },
    handleProductPricesOk( bool ){
      this.productPrices = {
        list: [],
        visible: false
      }
      if(bool) this.$refs.table.refresh()
    }
  },
  watch: {
    '$route.name': function (n, o) {
      this.pathName = n
      this.key++
    },
  },
}
</script>
<style scoped>
a {
}
</style>

 